import UserUtils from '@/utils/user';
import {VueConstructor} from 'vue';

/**
 * vue指令扩展
 */
export default {
  install(vue: VueConstructor) {
    /**
     * 权限判断
     * example: <i v-hasPermission="k1,k2"></i>
     */
    vue.directive('hasPermission', {
      inserted(el, binding) {
        let noPermission = true;
        const bindingValue = binding.value;
        let permissions = [] as string[];
        if (!bindingValue) {
          permissions = [];
        } else {
          permissions = ('' + bindingValue).split(',');
        }
        const isAdmin = UserUtils.getUser().admin;
        if (isAdmin) {
          noPermission = false;
        } else if (permissions.length > 0) {
          noPermission = !UserUtils.hasPermission(permissions);
        }
        if (noPermission) {
          const parentNode = el.parentNode;
          if (parentNode) {
            parentNode.removeChild(el);
          }
        }
      }
    });
    /**
     * 管理员判断
     * example: <i v-isAdmin></i>
     */
    vue.directive('isAdmin', {
      inserted(el) {
        if (!UserUtils.getUser().admin) {
          const parentNode = el.parentNode;
          if (parentNode) {
            parentNode.removeChild(el);
          }
        }
      }
    });
  }
};
